﻿using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Text;
using System.Web.Mvc;
using System.IO;
using System.Data.Objects;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using FILSTARTUPS_MOBILE.Models;
using FILSTARTUPS_MOBILE.Helpers;
using FILSTARTUPS_MOBILE.ViewModels;
using System.Web.Security;
using Microsoft.Web.Helpers;

namespace FILSTARTUPS_MOBILE.Controllers
{

 
    public class HomeController : Controller
    {
       
        //
        // GET: /Home/
        FilStatUpsEntities mobile_dbconnect = new FilStatUpsEntities();
        Mobile_Helpers mobile = new Mobile_Helpers();
        const int pageSize = 10;
        /*
         * Login Model or not
         * Parsing of Data Page, Category and Post
         * */
        public ActionResult Index()
        {
            try
            {
                var dataApi = new FilStartUpsApi();
                dataApi.PageNav = FilStartUps.GetPageNav();
                dataApi.NewsPost = FilStartUps.GetNewPost();
                dataApi.LatestPost = FilStartUps.GetLatestArticles();

                ViewBag.catidPK = 19;
                if (dataApi != null)
                {
                    return View(dataApi);
                }
                else
                {
                    //TODO ERROR PAGE
                    return View();
                }
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Comment(int id, string comment)
        {

            var user_ = mobile_dbconnect.Members.Where(m => m.emailaddress.Equals(User.Identity.Name)).SingleOrDefault();
                Comment comment_ = new Comment();
                comment_.postdescription = comment.Trim();
                comment_.postidFK = id;
                comment_.dateposted = DateTime.Now;
                comment_.memberidFK = user_.memberidPK;
                mobile_dbconnect.Comments.Add(comment_);
                mobile_dbconnect.SaveChanges();
                return RedirectToAction("Articles", new { postidPK= comment_.postidFK });
   
        }

        //, int? page
        public ActionResult Articles(int postidPK)
        {
            //Declaration
            //IQueryable<Comment> comments = null;

            //Instantiate Variable
            var categoryarticle = new CategoryPostArticle();
            //Retrieve API
            categoryarticle.PageNav = FilStartUps.GetPageNav();
            categoryarticle.categorypost = FilStartUps.GetArticleDetails(postidPK);
            categoryarticle.CatInfo = FilStartUps.GetPageSub(categoryarticle.categorypost.pageidFK);

            //Passing of value in comments variable
            //comments = FindComment(categoryarticle.categorypost.postidPK);
           
            //Adding Paging for Comments
            categoryarticle.Comments = (from c in mobile_dbconnect.Comments
                                        join m in mobile_dbconnect.Members
                                        on c.memberidFK equals m.memberidPK
                                        join p in mobile_dbconnect.Profiles
                                        on m.memberidPK equals p.memberidFK
                                        where c.postidFK.Equals(categoryarticle.categorypost.postidPK)
                                        select new UserComment
                                        {
                                            profileidFK=p.profileidPK,
                                            commentidPK=c.commentidPK,
                                            dateposted=c.dateposted,
                                            membername=m.emailaddress,
                                            postdescription=c.postdescription,
                                            postidFK=c.postidFK
                                        }).ToList();//FindComment(categoryarticle.categorypost.postidPK); //new PaginatedList<Comment>(comments, page ?? 0, pageSize);
           
            //var article_details = FilStartUps.GetArticleDetails(postidPK);
            if (categoryarticle != null)
            {
                return View(categoryarticle);
            }
            else
            {
                // TODO ERROR PAGE
                return View();
            }
        }
        /***
        public IQueryable<Comment> FindComment(int id)
        {
           return from c in mobile_dbconnect.Comments
                  orderby c.commentidPK descending
                  where c.postidFK.Equals(id)
                   select c;
        }***/

        public ActionResult Article(int catid, int? page)
        {
          
            try
            {
             //   IQueryable<Comment> comments = null;
                
                //Comment Paginated
                var categoryarticle = new CategoryPostArticle();
                categoryarticle.PageNav = FilStartUps.GetPageNav();
                categoryarticle.categorypost = FilStartUps.GetCategoryPost(catid);

              //  comments = FindComment(categoryarticle.categorypost.postidPK);

              //  categoryarticle.Comments = new PaginatedList<Comment>(comments, page ?? 0, pageSize);
                categoryarticle.Comments = (from c in mobile_dbconnect.Comments
                                            join m in mobile_dbconnect.Members
                                            on c.memberidFK equals m.memberidPK
                                            join p in mobile_dbconnect.Profiles
                                            on m.memberidPK equals p.memberidFK
                                            where c.postidFK.Equals(categoryarticle.categorypost.postidPK)
                                            orderby c.commentidPK descending
                                            select new UserComment
                                            {
                                                profileidFK = p.profileidPK,
                                                commentidPK = c.commentidPK,
                                                dateposted = c.dateposted,
                                                membername = m.emailaddress,
                                                postdescription = c.postdescription,
                                                postidFK = c.postidFK
                                            }).ToList();

                categoryarticle.CatInfo = FilStartUps.GetPageSub(categoryarticle.categorypost.pageidFK);

                if (categoryarticle != null)
                {
                    return View(categoryarticle);
                }
                else
                {
                    //ERROR PAGE
                    return View();
                }
            }
            catch
            {
                Response.Write("Error");
                return null;
            }
           
        }

        public ActionResult Login()
        {  
            return View();
        }

        //ERROR MESSAGE
        [HttpPost]
        public ActionResult Login(FormCollection form)
        {
            
           string emailaddress_ = form["emailaddress"].Trim();
           string password_ = form["password"].Trim();

           var checkuser = mobile_dbconnect.Members.Where(m => m.emailaddress.Equals(emailaddress_) 
                           && m.password.Equals(password_)
                           && m.member_flag.Equals(true)).SingleOrDefault();
            /**
           if (checkuser.member_flag.Equals(false))
           {
               // Validation for inactive user. View Link For Activation or resend new code
               return View();
           }**/
           
            var user_role = mobile_dbconnect.Roles.Where(r=>r.roleidPK.Equals(checkuser.roleidFK)).SingleOrDefault();
            if(checkuser != null)
            {
                bool Authenticate_User = Authenticate(checkuser.emailaddress, user_role.rolename);
                    if(Authenticate_User == true)
                    {                             
                        // Forms Authentication and Session
                         return RedirectToAction("Index");
                    }
            }
            else
            {
                //User Validation
              return View();
            }

            return View();
        }

        public ActionResult Registration()
        {
           return View();
        }

        //Validation + Captcha
        [HttpPost]
        public ActionResult Registration(Member member, Profile profile, FormCollection form)
        {
            string activationkey = Mobile_Helpers.Create();    
            try
            {
                if (ModelState.IsValid)
                {
                    member.datejoined = DateTime.Now;
                    member.roleidFK = 1;
                    member.validationcode = activationkey;
                    member.member_flag = false;
                    member.secretquestion = form["secretquestion"].Trim();

                    var checkuser_ = mobile_dbconnect.Members.Where(m => m.emailaddress.Equals(member.emailaddress)).ToList();
                    
                    if(checkuser_.Count() > 0)
                    {
                        TempData["message"] = string.Format("Email Address is already been used!");
                        return View();
                    }

                    mobile_dbconnect.Members.Add(member);
                    mobile_dbconnect.SaveChanges();

                    profile.memberidFK = member.memberidPK;
                    mobile_dbconnect.Profiles.Add(profile);
                    mobile_dbconnect.SaveChanges();
                    return RedirectToAction("Index");

                    /*
                     * EMAIL USER
                     * VIEW That an email has been sent.
                     * return RedirectToAction("Activation View");
                     * */
                }
            }
            catch 
            {
                return View();
            }
            return View();
        }

        public ActionResult Logout()
        {
            Session.Abandon();
            FormsAuthentication.SignOut();

            return RedirectToAction("Index");
        }

        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ForgotPassword(ForgotPasswordModel forgot, FormCollection form)
        {
            try
            {
                string email = form["emailaddress"].Trim();
                string confirmemail = form["confirmemailaddress"].Trim();
                string secretquestion = form["secretquestion"].Trim();
                string secretanswer = form["secretanswer"].Trim();
            
                var forgotpassword = (from m in mobile_dbconnect.Members
                                      where m.emailaddress.Equals(email)
                                      && m.confirmemailaddress.Equals(confirmemail)
                                      && m.secretquestion.Equals(secretquestion)
                                      && m.secretanswer.Equals(secretanswer)
                                      select m).SingleOrDefault();
         
                if (forgotpassword != null)
                {
                    //Send New Password email
                    //Password Generator
                    //Update Database => Password -->Member_Table
                    return View();
                }
                else
                {
                    return View(forgotpassword);
                }
                
            }
            catch
            {
                return null;
            }
            
        }

        // Succes Page
        public ActionResult Success()
        {
            /*if(1)=registration 
             * 
             * */
            return View();
        }

        /************ ACTIVATION VIEW ************/
        public ActionResult Activation(string email, string qs, string rurl)
        {
            string email_ = Request.QueryString["email"].Trim();
            string activationkey = Request.QueryString["qs"].Trim();
            string url_ = Request.QueryString["rurl"].Trim();

            /*
             * Message Edit Profile  
             * Sample Message : Thank you, Username/EmailAddress. Your registration is now complete.
             *                  Alternatively, you can simply go back to the Forums and start posting in threads.
             * Option Profile - Forums
             * */
            return View();
        }

        //Final
        //Removed pagename
        public ActionResult Page(int pageidPK)
        {
            int pageid_PK = Convert.ToInt32(Request.QueryString["pageidPK"].Trim());

            var page = new PageInformation();

            page.pageinfo = FilStartUps.GetPageInfo(pageid_PK);
            page.PageNav = FilStartUps.GetPageNav();
            page.CatInfo = FilStartUps.GetPageSub(pageid_PK);
            if (page.pageinfo != null)
            {
                return View(page);
            }
            else
            {
                //Page Not Found
                return View();
            }
            
        }
        //Pagination Credits Nerds
        public ActionResult PostArchieves(int catidPK,int? page)
        {
            const int pageSize = 10;
            //if (page == null)
            //{
            //    page = 1;
            //}
            //else
            //{
            //    if (next == true)
            //    {
            //        page++;
            //    }
            //    else if (next == false)
            //    {
            //        page--;
            //    }
            //}
            IQueryable<PostInfo> Posts = null;
           

            Posts = FilStartUps.GetArticleArchieves(catidPK).AsQueryable();

            var paginatedArticles = new PaginatedList<PostInfo>(Posts, page ?? 0, pageSize);
            //ViewBag.catid = catidFK;
            //ViewBag.page = page;

            if (paginatedArticles != null)
            {
                return View(paginatedArticles);
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        #region SEMI HELPER
        /*** SEMI HELPER ***/
        public JsonResult EmailExists(string emailaddress)
        {
            var user = mobile_dbconnect.Members.Where(m => m.emailaddress.Equals(emailaddress.Trim())).SingleOrDefault();
            return user == null ? Json(true, JsonRequestBehavior.AllowGet) :
                                Json(string.Format("Email Address is already been used!", emailaddress),
                                    JsonRequestBehavior.AllowGet);

        }



        private bool Authenticate(string username, string rolename)
        {

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,
                username,
                DateTime.Now,
                DateTime.Now.AddMinutes(60),
                false,
                rolename,
                FormsAuthentication.FormsCookiePath);

            string hash = FormsAuthentication.Encrypt(ticket);

            HttpCookie cookie = new HttpCookie(
                FormsAuthentication.FormsCookieName,
                hash);

            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

            Response.Cookies.Add(cookie);

            return true;
        }

        #endregion  
    }
}
